import java.util.*;

public class Solution778 {
    int result=0;
    int[] R=new int[]{1,0,-1,0};
    int[] C=new int[]{0,1,0,-1};

    public void travel(int[][] grid,int m,int n,int tmpMax,int[][] mark){
        if(result!=0&&tmpMax>=result){
            return;
        }
        if(m== grid.length-1&&n== grid[0].length-1){
            result=tmpMax;
            return;
        }
        List<int[]>  queue=new ArrayList<>();
        for (int i = 0; i < R.length; i++) {
            int newM=m+R[i];
            int newN=n+C[i];
            if(0<=newM&&newM< grid.length&&0<=newN&&newN< grid[0].length) {
                if (mark[newM][newN] == 1) {
                    continue;
                }
                queue.add(new int[]{i,grid[newM][newN]});
            }
        }
        Collections.sort(queue, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1]-o2[1];
            }
        });
        for (int[] tmp:queue) {
            int newM=m+R[tmp[0]];
            int newN=n+C[tmp[0]];
            mark[newM][newN]=1;
            travel(grid,newM,newN,Math.max(tmpMax,grid[newM][newN]),mark);
            mark[newM][newN]=0;
        }
    }

    public int swimInWater(int[][] grid) {
        int[][] markPath=new int[grid.length][grid[0].length];
        travel(grid,0,0,grid[0][0],markPath);
        return result;
    }

    public static void main(String[] args) {
        Solution778 s=new Solution778();
        System.out.println(s.swimInWater(new int[][]{{0,2},{1,3}}));
    }
}
